package org.example;

import java.io.*;
import java.util.*;

public class FileUtil {
    private static final String FILE_PATH = "students.dat";

    // 保存学生数据到文件
    public static void saveStudents(List<Student> students) {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(FILE_PATH))) {
            oos.writeObject(students);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("保存数据失败");
        }
    }

    // 从文件加载学生数据
    @SuppressWarnings("unchecked")
    public static List<Student> loadStudents() {
        File file = new File(FILE_PATH);
        if (!file.exists()) {
            return new ArrayList<>();
        }

        try (ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(file))) {
            return (List<Student>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
}
